<script setup lang="ts">
import useUnitStore from '@/stores/unit'
import { computed, ref, watch } from 'vue'
import useUserStore from '@/stores/user'
import { PageParam } from '@/type'
import { getUnitByLazy } from '@/api/sys/unit'

const model = defineModel()
const unitStore = useUnitStore()
const userStore = useUserStore()
const emit = defineEmits(['change'])

const {
  permission,
  disabled = false,
  placeholder = '请选择组织单位',
  unitId,
} = defineProps<{
  permission?: string
  placeholder?: string
  disabled?: boolean
  unitId?: number
}>()

const departmentList = ref([])

watch(
  () => unitId,
  async () => {
    if (!unitId) {
      departmentList.value = []
      return
    }
    const postData: PageParam = {
      currentPage: 0,
      pageSize: 0,
      sort: [],
      query: {
        node: unitId,
      },
    }

    const { data } = await getUnitByLazy(postData)
    if (data.status === 200 && data.data.length !== 0) {
      departmentList.value =
        data.data.map((item: any) => {
          return {
            id: item.id,
            name: item.unitForShort,
          }
        }) || []
    } else {
      departmentList.value = []
    }
  },
  {
    immediate: true,
  },
)

const filterList = computed<{ id: number; name: string }[]>(() => {
  if (!permission) return allUnitList.value
  const ids = userStore.getPermissionId(permission)
  if (ids) {
    return allUnitList.value.filter((item) => ids.includes(item.id))
  } else {
    return []
  }
})

const allUnitList = computed<{ id: number; name: string }[]>(() => {
  return unitId ? departmentList.value : unitStore.list
})

const list = computed<{ id: number; name: string }[]>(() => {
  if (userStore.isAdmin === 1) {
    return allUnitList.value
  } else if (permission) {
    return filterList.value
  } else {
    return allUnitList.value
  }
})

function handleChange(value: any) {
  emit('change', value)
}
</script>
<template>
  <el-select
    class="unit-select"
    v-model="model"
    :disabled="disabled"
    :placeholder="placeholder"
    clearable
    filterable
    @change="handleChange"
  >
    <el-option
      v-for="item in list"
      :key="item.id"
      :label="item.name"
      :value="item.id"
    />
  </el-select>
</template>
<style scoped lang="scss"></style>
